﻿using Chip8.Core.Bus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Chip8.Core.Processor.Operations;

namespace Chip8.Core.Input
{
	internal class ConsoleKeypad : Device, IKeypad
	{
		private const int KeypadSize = 16;

		public ConsoleKeypad(SystemBus bus)
			: base(bus)
		{

		}

		public override void Reset()
		{
			Array.Clear(_keys, 0, KeypadSize);
		}

		public override void Tick()
		{
			Array.Clear(_keys, 0, KeypadSize);

			while (Console.KeyAvailable)
			{
				var cki = Console.ReadKey(true);
				int keyIndex;
				if (_keymap.TryGetValue(cki.Key, out keyIndex))
				{
					_keys[keyIndex] = true;
				}
			}
		}

		public bool CheckKey(int keyIndex)
		{
			if (0 < keyIndex && keyIndex < KeypadSize)
			{
				return _keys[keyIndex];
			}

			return false;
		}

		public int WaitKey()
		{
			while (true)
			{
				var cki = Console.ReadKey(true);
				int keyIndex;
				if (_keymap.TryGetValue(cki.Key, out keyIndex))
				{
					return keyIndex;
				}
			}
		}

		private readonly bool[] _keys = new bool[KeypadSize];
		private readonly Dictionary<ConsoleKey, int> _keymap = new Dictionary<ConsoleKey, int>
		                                        {
			                                        {ConsoleKey.X,	0x00},
			                                        {ConsoleKey.D1,	0x01},
			                                        {ConsoleKey.D2,	0x02},
			                                        {ConsoleKey.D3,	0x03},
			                                        {ConsoleKey.Q,	0x04},
			                                        {ConsoleKey.W,	0x05},
			                                        {ConsoleKey.E,	0x06},
			                                        {ConsoleKey.A,	0x07},
			                                        {ConsoleKey.S,	0x08},
			                                        {ConsoleKey.D,	0x09},
			                                        {ConsoleKey.Z,	0x0A},
			                                        {ConsoleKey.C,	0x0B},
			                                        {ConsoleKey.D4,	0x0C},
			                                        {ConsoleKey.R,	0x0D},
			                                        {ConsoleKey.F,	0x0E},
			                                        {ConsoleKey.V,	0x0F}
		                                        };
	}
}
